
<template>
  <div>
    <el-card shadow="always" :body-style="{ padding: '20px' }" :style="{ margin: '20px' }">
      <el-form ref="form" label-width="80px" :inline="false" size="default">
        <el-form-item label="Spu名称">
          <el-input v-model="spuInfo.spuName"></el-input>
        </el-form-item>
        <el-form-item label="品牌">
          <el-select value-key="" v-model="(spuInfo.tmId as number)" placeholder="" clearable filterable @change="">
            <el-option v-for=" tm in tmList" :key="tm.id" :value="tm.id" :label="tm.tmName" />
          </el-select>
        </el-form-item>
        <el-form-item label="Spu描述">
          <el-input type="textarea" v-model="spuInfo.description" placeholder="" clearable @change=""></el-input>
        </el-form-item>
        <el-form-item label="Spu图片">
          <!-- 图片内置类型 -->
          <el-upload v-model:file-list="(spuImageList as UploadUserFile[])" :action="`${baseUrl}/admin/product/upload`"
            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>

        <el-form-item label="销售属性">
          <el-select value-key="" v-model="tempSaleAttr" :placeholder="`还有${unUsedSaleAttrList.length}个未选`" clearable
            filterable @change="">
            <el-option v-for=" sale in unUsedSaleAttrList" :key="sale.id" :value="`${sale.id}:${sale.name}`"
              :label="sale.name" />
          </el-select>
          <el-button type="primary" size="default" :disabled="!tempSaleAttr" @click="addSaleAttr">添加销售属性
          </el-button>
        </el-form-item>


        <!-- 表单 -->
        <el-form-item label="" size="default">
          <el-table :data="spuSaleAttrList" border stripe inline>
            <el-table-column label="序号" type="index" width="50" />
            <el-table-column prop="saleAttrName" label="属性名"></el-table-column>
            <el-table-column label="属性名称列表">
              <template v-slot="{ row }">
                <!-- @close="handleClose(tag)" -->
                <el-tag v-for="tag,index in row.spuSaleAttrValueList" :key="tag.id" class="mx-1" closable
                  :disable-transitions="false" @close="row.spuSaleAttrValueList.splice(index, 1)">
                  {{ tag.saleAttrValueName }}
                </el-tag>

                <el-input class="ml-1 w-20" v-model="row.inputValue" size="small" @blur="changeToSee(row,$event)"
                  @focus="getFocus(row)" v-if="row.isEdit" ref="editEle" />

                <el-button class="button-new-tag ml-1" size="small" v-else @click="changeToEdit(row)">
                  + 新增属性值
                </el-button>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template v-slot="{ row,$index }">
                <el-button type="danger" @click="spuSaleAttrList.splice($index, 1)" size="small" icon="ele-Delete">
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="save">保存</el-button>
          <el-button @click="emit('setState', 0)">取消</el-button>
        </el-form-item>
      </el-form>



      

    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: 'SpuForm',
});
</script>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick } from 'vue'
import { Plus } from '@element-plus/icons-vue'

import {
  requestBaseSaleAttrList,
  requestDeleteSpu,
  requestSaveSpuInfo,
  requestSpuImgList,
  requestSpuSaleAttrList,
  requestUpdateSpuInfo,
  type SpuSaleAttrItemType,
  type SpuSaleAttrValueItemType,
  type SpuSaleAttrValueListType,
} from "@/api/spu";
import type {
  BaseSaleAttrListType,
  SpuImgListType,
  SpuSaleAttrListType,
  SpuInfoType
} from "@/api/spu";
import type { UploadProps, UploadUserFile } from "element-plus";
import { ElMessage } from "element-plus";

import { requestAllTmList } from "@/api/trademark";
import type { TmListType } from "@/api/trademark";


/* 拿到对应环境的 代理前缀 */
const baseUrl = import.meta.env.VITE_API_URL;
// :action="`${baseUrl}/admin/product/upload`"


//3.图片区域🐟🐟🐟🐟
// const fileList = ref<UploadUserFile[]>([
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
//   {
//     name: 'food.jpeg',
//     url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100',
//   },
// ])

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
  //删除的时候uploadFiles就是最新的数组
  // spuImageList.value = uploadFiles as any;
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}


//接受自定义事件
const emit = defineEmits<{
  (event: "setState", state: number, row?: SpuInfoType): void
}>()

//接受props传来的数据
const props = defineProps<{
  spuInfo: SpuInfoType;
}>()


//发送请求获取数据
//3.根据新增还是修改去请求当前Form需要的数据(其中新增需要发送:1.品牌列表2.所有销售属性列表,修改需要发送:1.品牌列表2.所有销售属性列表3.当前spu图片列表4.当前spu的属性列表)
//声明一些数据 保存品牌列表 所有销售属性列表,当前spu图片列表,当前spu的属性列表
const tmList = ref<TmListType[]>([]); //品牌列表
const saleAttrList = ref<BaseSaleAttrListType>([]); //销售属性列表
const spuImageList = ref<SpuImgListType>([]); //图片列表
const spuSaleAttrList = ref<SpuSaleAttrListType>([]); //销售属性 值 列表

// 封装请求表单需要函数
const getAllUseData = async () => {
  if (!props.spuInfo.id) {
    try {
      //新增逻辑,发送两个请求
      const result1 = await requestAllTmList();
      tmList.value = result1;
      const result2 = await requestBaseSaleAttrList();
      saleAttrList.value = result2;
    } catch (e) {
      ElMessage.error("品牌请求或者属性列表请求失败");
    }
  } else {
    //修改逻辑,发送四个请求
    const promise1 = requestAllTmList();
    const promise2 = requestBaseSaleAttrList();
    const promise3 = requestSpuImgList(props.spuInfo.id);
    const promise4 = requestSpuSaleAttrList(props.spuInfo.id);

    try {
      const result = await Promise.all([
        promise1,
        promise2,
        promise3,
        promise4,
      ]);
      tmList.value = result[0];
      saleAttrList.value = result[1];

      spuImageList.value = result[2];
      //给图片赋值 需要的属性
      spuImageList.value.forEach((item) => {
        item.name = item.imgName
        item.url = item.imgUrl
      })
      spuSaleAttrList.value = result[3];
      spuSaleAttrList.value.forEach((item) => {
        item.inputValue = item.inputValue
        item.isEdit = item.isEdit
      })



    } catch (e) {
      ElMessage.error("初始请求失败");
    }
  }
}


//初始化请求数据
onMounted(() => {
  getAllUseData();
})

//计算属性计算没有使用的销售属性列表

//定义 一个  销售属性 准备添加去到数组中 
const tempSaleAttr = ref("")
//添加销售属性事件
const addSaleAttr = () => {
  const [baseSaleAttrId, saleAttrName] = tempSaleAttr.value.split(':')
  const tempSpuSaleAttr = {
    /* 转number类型 + */
    baseSaleAttrId: +baseSaleAttrId,
    saleAttrName: saleAttrName,
    spuSaleAttrValueList: []
  }
  //把添加的值 传入 请求列表的数组中
  spuSaleAttrList.value.push(tempSpuSaleAttr)
  /* 清除临时数据 */
  tempSaleAttr.value = ""
}

//计算属性
const unUsedSaleAttrList = computed(() => {
  //处理处理,删除当前spu已经拥有的销售属性
  return saleAttrList.value.filter((item1) => {
    //我们给你一个销售属性对象,我想判断当前的spu销售属性列表里有没有和我一样的,如果没有则返回true,如果有则返回false
    return spuSaleAttrList.value.every((item2) => {
      return item2.saleAttrName !== item1.name;
    });
  });
})



//获取input DOM元素
const editEle = ref<HTMLInputElement>()

//to编辑模式
const changeToEdit = (row: SpuSaleAttrItemType) => {
  row.isEdit = true
  //自动获取焦点
  nextTick(() => {
    (editEle.value as HTMLInputElement).focus()
  })
}
//to查看模式
const changeToSee = (row: SpuSaleAttrItemType,e:Event) => {
  //获取当前框的内容 
  let inputValue = row.inputValue as string
  // console.log("row.inputValue",row.inputValue)
    //判断当前的内容是否为空
    console.log("inputValue",inputValue)
    if (!inputValue.trim()) {
    row.isEdit = false;
    ElMessage.error("添加的属性值为空");
    return;
  }
  //判断输入框的内容是否有重复
  const isRepeat = row.spuSaleAttrValueList.some((item)=>{
    return item.saleAttrValueName === inputValue
  })
  //重复
  if(isRepeat){
    ElMessage.error("添加的属性值有重复");
    //关闭输入框
    row.isEdit = false;
    //清空之前的值
    row.inputValue = "";
    return 
  }
  //把值填到列表
  //整理以下要添加到row的属性值列表中的数据
  const newSaleAttrValue = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputValue as string,
  };

  row.spuSaleAttrValueList.push(newSaleAttrValue);

 //最后要清空并切换到按钮模式
 row.isEdit = false;
  row.inputValue = "";
}

//获取焦点事件
const getFocus = (row: SpuSaleAttrValueItemType) => {
}
//整理图片数据
const save =  async()=>{
  //整理图片数据
  const newSpuImageList = spuImageList.value.map((item)=>{
    // let obj  = {}
    if(item.response){
      return {
        imgName:item.name as string,
        imgUrl:item.response.data as string
      }
    }else{
      return {
        imgName:item.imgName,
        imgUrl:item.imgUrl
      }
    }
  })
  // console.log(newSpuImageList);

  //整理SaleAttrvalueList 数据 因为 多了 isEdit he inputValue 删除
  spuSaleAttrList.value.forEach((item)=>{
    delete item.inputValue
    delete item.isEdit
  })

  //把整理的两个值添加到spuInfo上
  props.spuInfo.spuImageList = newSpuImageList
  props.spuInfo.spuSaleAttrList =spuSaleAttrList.value

  //提交数据
  try{
    if(props.spuInfo.id){
    //更新
    await requestUpdateSpuInfo(props.spuInfo)
  }else{
    //禁止提交
    if(!props.spuInfo.spuName){
      alert("不能为空")
      return 
    }
    //新增
    await requestSaveSpuInfo(props.spuInfo)
  }
  }catch(e){
    ElMessage.error("新增或更新数据")
  }
  //会到列表页
  emit('setState',0)
}






</script>